package cn.com.nr.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasStationinfoService;
import cn.com.nr.entity.NrCamchangeEntity;
import cn.com.nr.entity.NrConcreteEndangerEntity;
import cn.com.nr.entity.NrDiggingsEndangerEntity;
import cn.com.nr.service.NrCamchangeService;
import cn.com.nr.service.NrConcreteEndangerService;
import cn.com.nr.service.NrDiggingsEndangerService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.HmacSha256Utils;
import cn.com.util.HttpUtils;
import cn.com.util.MD5Utils;
import cn.com.util.TsBqUtils;



/**
 * 摄像头变动
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2025-04-08 13:29:27
 */
@Controller
@RequestMapping("/nr/camchange")
@Slf4j
public class NrCamchangeController {
	@Autowired
	private NrCamchangeService nrCamchangeService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private NrDiggingsEndangerService nrDiggingsEndangerService;
	@Autowired
	private NrConcreteEndangerService nrConcreteEndangerService;
	
	@Autowired
	private HttpSessionService httpSessionService;
	@Value("${gasstation.thirdPartyPass}")
	private String pass;
	@Value("${gasstation.thirdPartyUser}")
	private String user;
	@Value("${gasstation.configCamAIAnalyseSceneChangeAckUrl}")
	private String url;

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	@ResponseBody
	public DataResult update(@RequestBody NrCamchangeEntity nrCamchange) throws Exception {

		String currentUserId = httpSessionService.getCurrentUserId();
		String handleType = nrCamchange.getHandleType();
		String handleReason = nrCamchange.getHandleReason();

		String id = nrCamchange.getId();
		NrCamchangeEntity nrCamchangeEntity = nrCamchangeService.getById(id);

		if (TsBqUtils.isNull(handleType)) {
			return DataResult.fail("处理类型未选择！");
		}

		if (TsBqUtils.isNull(handleReason)) {
			return DataResult.fail("原因未填写！");
		}

		nrCamchangeEntity.setHandleType(handleType);
		nrCamchangeEntity.setHandleReason(handleReason);
		nrCamchangeEntity.setHandleImage(nrCamchange.getHandleImage());
		nrCamchangeEntity.setUpdateId(currentUserId);
		nrCamchangeEntity.setUpdateTime(new Date());
		nrCamchangeService.updateById(nrCamchangeEntity);
		// 反馈到底层

		/*
		 * camerainfo=[{"camid":206627,"groupid":
		 * "07f23824-bb9a-471f-9219-19f708db0679","acked":1}]
		 */

		List<Map<String, Object>> listmap = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("camid", Integer.valueOf(nrCamchange.getMessageCamid()));
		map.put("groupid", nrCamchange.getMessageGroupid());
		map.put("acked", 1);
		listmap.add(map);
		String jsonString = JSON.toJSONString(listmap);
		log.info("NrCamchange请求报文："+jsonString);
		String _url = url+"?api="+user+"&sign=OEgPWMjS1dBkepHXG9BkbpE4PFJZxGoNDpO%2BTC%2BBLTQ%3D";
		log.info("NrCamchange请求URL："+_url);
		String doPost = HttpUtils.doPost(_url, jsonString);
		log.info("NrCamchange请求结果res:" + doPost);
		
		return DataResult.success();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据(未处理)")
	@PostMapping("/list1")
	@ResponseBody
	public DataResult list1(@RequestBody NrCamchangeEntity nrCamchange) throws ParseException {
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();
		String taxorgcode = nrCamchange.getTaxorgcode();
		
		String stationinfoName = nrCamchange.getStationinfoName();
		String industry =  nrCamchange.getIndustry();
		
		List<String> stationinfoIdList = new ArrayList<>();
		if(TsBqUtils.isNull(industry)){
			// 查询所有的
			// 查询矿山
			LambdaQueryWrapper<NrDiggingsEndangerEntity> nrDiggingsEndangerWrappers = Wrappers.lambdaQuery();			
			if(TsBqUtils.isNotNull(stationinfoName)){
				nrDiggingsEndangerWrappers.like(NrDiggingsEndangerEntity::getName, stationinfoName);
			}
			List<NrDiggingsEndangerEntity> nrDiggingsList = nrDiggingsEndangerService.list(nrDiggingsEndangerWrappers);
			
			if(TsBqUtils.isNotNull(nrDiggingsList)){
				for (NrDiggingsEndangerEntity nrDiggingsEndangerEntity : nrDiggingsList) {
					stationinfoIdList.add(nrDiggingsEndangerEntity.getId());
				}
			}
			
			// 查询混凝土和水泥
			LambdaQueryWrapper<NrConcreteEndangerEntity> nrConcreteEndangerWrappers = Wrappers.lambdaQuery();
			if(TsBqUtils.isNotNull(stationinfoName)){
				nrConcreteEndangerWrappers.like(NrConcreteEndangerEntity::getName, stationinfoName);
			}
			List<NrConcreteEndangerEntity> nrConcreteList = nrConcreteEndangerService.list(nrConcreteEndangerWrappers);			
			if(TsBqUtils.isNotNull(nrConcreteList)){
				for (NrConcreteEndangerEntity nrConcreteEndangerEntity : nrConcreteList) {
					stationinfoIdList.add(nrConcreteEndangerEntity.getId());
				}
			}
			
		}else{
			if("铁矿采矿".equals(industry)||"铁矿选矿".equals(industry)){
				LambdaQueryWrapper<NrDiggingsEndangerEntity> nrDiggingsEndangerWrappers = Wrappers.lambdaQuery();			
				if(TsBqUtils.isNotNull(stationinfoName)){
					nrDiggingsEndangerWrappers.like(NrDiggingsEndangerEntity::getName, stationinfoName);
				}
				nrDiggingsEndangerWrappers.eq(NrDiggingsEndangerEntity::getIndustry, industry);
				List<NrDiggingsEndangerEntity> nrDiggingsList = nrDiggingsEndangerService.list(nrDiggingsEndangerWrappers);
				
				if(TsBqUtils.isNotNull(nrDiggingsList)){
					for (NrDiggingsEndangerEntity nrDiggingsEndangerEntity : nrDiggingsList) {
						stationinfoIdList.add(nrDiggingsEndangerEntity.getId());
					}
				}      	
		
			}else if("水泥制造".equals(industry)||"混凝土".equals(industry)){
				
				LambdaQueryWrapper<NrConcreteEndangerEntity> nrConcreteEndangerWrappers = Wrappers.lambdaQuery();
				if(TsBqUtils.isNotNull(stationinfoName)){
					nrConcreteEndangerWrappers.like(NrConcreteEndangerEntity::getName, stationinfoName);
				}
				nrConcreteEndangerWrappers.eq(NrConcreteEndangerEntity::getIndustry, industry);

				List<NrConcreteEndangerEntity> nrConcreteList = nrConcreteEndangerService.list(nrConcreteEndangerWrappers);			
				if(TsBqUtils.isNotNull(nrConcreteList)){
					for (NrConcreteEndangerEntity nrConcreteEndangerEntity : nrConcreteList) {
						stationinfoIdList.add(nrConcreteEndangerEntity.getId());
					}
				}
		
			}else {
				return DataResult.fail("入参industry不合法！");
			}
		}

		if(TsBqUtils.isNull(stationinfoIdList)){
			return DataResult.fail("未查询到企业！");	
		}
		
		String createTimeStart = nrCamchange.getCreateTimeStart();
		String createTimeEnd = nrCamchange.getCreateTimeEnd();

		Page page = new Page(nrCamchange.getPage(), nrCamchange.getLimit());
		LambdaQueryWrapper<NrCamchangeEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (!StringUtils.isEmpty(createTimeStart)) {
			queryWrapper.ge(NrCamchangeEntity::getCreateTime, sdf.parse(createTimeStart + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(createTimeEnd)) {
			queryWrapper.le(NrCamchangeEntity::getCreateTime, sdf.parse(createTimeEnd + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(taxorgcode)) {
			queryWrapper.eq(NrCamchangeEntity::getHandleTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(NrCamchangeEntity::getHandleTaxorgcode, currentDeptId);
			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.like(NrCamchangeEntity::getHandleTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}
		
		if(TsBqUtils.isNotNull(stationinfoIdList)){
			queryWrapper.in(NrCamchangeEntity::getMessageGroupid, stationinfoIdList);
		}
		
		queryWrapper.isNull(NrCamchangeEntity::getHandleType);

		IPage<NrCamchangeEntity> iPage = nrCamchangeService.page(page, queryWrapper);
		List<NrCamchangeEntity> records = iPage.getRecords();
		for (NrCamchangeEntity camchangeEntity : records) {
			String messageGroupid = camchangeEntity.getMessageGroupid();
			GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(messageGroupid);
			if (TsBqUtils.isNotNull(stationinfoEntity)) {
				String name = stationinfoEntity.getName();
				camchangeEntity.setStationinfoName(name);
				
				String taxpayerCode = stationinfoEntity.getTaxpayerCode();
				
				camchangeEntity.setTaxpayerCode(taxpayerCode);
			}

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据(已处理)")
	@PostMapping("/list2")
	@ResponseBody
	public DataResult list2(@RequestBody NrCamchangeEntity nrCamchange) throws ParseException {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		String currentDeptId = httpSessionService.getCurrentDeptId();
		String taxorgcode = nrCamchange.getTaxorgcode();
		String stationinfoName = nrCamchange.getStationinfoName();
		String industry =  nrCamchange.getIndustry();		
		List<String> stationinfoIdList = new ArrayList<>();
		if(TsBqUtils.isNull(industry)){
			// 查询所有的
			// 查询矿山
			LambdaQueryWrapper<NrDiggingsEndangerEntity> nrDiggingsEndangerWrappers = Wrappers.lambdaQuery();			
			if(TsBqUtils.isNotNull(stationinfoName)){
				nrDiggingsEndangerWrappers.like(NrDiggingsEndangerEntity::getName, stationinfoName);
			}
			List<NrDiggingsEndangerEntity> nrDiggingsList = nrDiggingsEndangerService.list(nrDiggingsEndangerWrappers);
			
			if(TsBqUtils.isNotNull(nrDiggingsList)){
				for (NrDiggingsEndangerEntity nrDiggingsEndangerEntity : nrDiggingsList) {
					stationinfoIdList.add(nrDiggingsEndangerEntity.getId());
				}
			}
			
			// 查询混凝土和水泥
			LambdaQueryWrapper<NrConcreteEndangerEntity> nrConcreteEndangerWrappers = Wrappers.lambdaQuery();
			if(TsBqUtils.isNotNull(stationinfoName)){
				nrConcreteEndangerWrappers.like(NrConcreteEndangerEntity::getName, stationinfoName);
			}
			List<NrConcreteEndangerEntity> nrConcreteList = nrConcreteEndangerService.list(nrConcreteEndangerWrappers);			
			if(TsBqUtils.isNotNull(nrConcreteList)){
				for (NrConcreteEndangerEntity nrConcreteEndangerEntity : nrConcreteList) {
					stationinfoIdList.add(nrConcreteEndangerEntity.getId());
				}
			}
			
		}else{
			if("铁矿采矿".equals(industry)||"铁矿选矿".equals(industry)){
				LambdaQueryWrapper<NrDiggingsEndangerEntity> nrDiggingsEndangerWrappers = Wrappers.lambdaQuery();			
				if(TsBqUtils.isNotNull(stationinfoName)){
					nrDiggingsEndangerWrappers.like(NrDiggingsEndangerEntity::getName, stationinfoName);
				}
				nrDiggingsEndangerWrappers.eq(NrDiggingsEndangerEntity::getIndustry, industry);
				List<NrDiggingsEndangerEntity> nrDiggingsList = nrDiggingsEndangerService.list(nrDiggingsEndangerWrappers);
				
				if(TsBqUtils.isNotNull(nrDiggingsList)){
					for (NrDiggingsEndangerEntity nrDiggingsEndangerEntity : nrDiggingsList) {
						stationinfoIdList.add(nrDiggingsEndangerEntity.getId());
					}
				}      	
		
			}else if("水泥制造".equals(industry)||"混凝土".equals(industry)){
				
				LambdaQueryWrapper<NrConcreteEndangerEntity> nrConcreteEndangerWrappers = Wrappers.lambdaQuery();
				if(TsBqUtils.isNotNull(stationinfoName)){
					nrConcreteEndangerWrappers.like(NrConcreteEndangerEntity::getName, stationinfoName);
				}
				nrConcreteEndangerWrappers.eq(NrConcreteEndangerEntity::getIndustry, industry);

				List<NrConcreteEndangerEntity> nrConcreteList = nrConcreteEndangerService.list(nrConcreteEndangerWrappers);			
				if(TsBqUtils.isNotNull(nrConcreteList)){
					for (NrConcreteEndangerEntity nrConcreteEndangerEntity : nrConcreteList) {
						stationinfoIdList.add(nrConcreteEndangerEntity.getId());
					}
				}
		
			}else {
				return DataResult.fail("入参industry不合法！");
			}
		}
		
		
		
		String createTimeStart = nrCamchange.getCreateTimeStart();
		String createTimeEnd = nrCamchange.getCreateTimeEnd();
		// String stationinfoName = gasCamchange.getStationinfoName();

		Page page = new Page(nrCamchange.getPage(), nrCamchange.getLimit());
		LambdaQueryWrapper<NrCamchangeEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (!StringUtils.isEmpty(createTimeStart)) {
			queryWrapper.ge(NrCamchangeEntity::getCreateTime, sdf.parse(createTimeStart + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(createTimeEnd)) {
			queryWrapper.le(NrCamchangeEntity::getCreateTime, sdf.parse(createTimeEnd + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(taxorgcode)) {
			queryWrapper.eq(NrCamchangeEntity::getHandleTaxorgcode, taxorgcode);

		} else {
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 县区局
				queryWrapper.eq(NrCamchangeEntity::getHandleTaxorgcode, currentDeptId);
			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
				// 市局
				queryWrapper.like(NrCamchangeEntity::getHandleTaxorgcode, currentDeptId.substring(0, 5));
			} else {
				// 省局
			}
		}
		
		if(TsBqUtils.isNotNull(stationinfoIdList)){
			queryWrapper.in(NrCamchangeEntity::getMessageGroupid, stationinfoIdList);
		}
		
		queryWrapper.isNotNull(NrCamchangeEntity::getHandleType);

		IPage<NrCamchangeEntity> iPage = nrCamchangeService.page(page, queryWrapper);
		List<NrCamchangeEntity> records = iPage.getRecords();
		for (NrCamchangeEntity camchangeEntity : records) {
			String messageGroupid = camchangeEntity.getMessageGroupid();
			GasStationinfoEntity stationinfoEntity = gasStationinfoService.getById(messageGroupid);
			if (TsBqUtils.isNotNull(stationinfoEntity)) {
				String name = stationinfoEntity.getName();
				camchangeEntity.setStationinfoName(name);
				
				String taxpayerCode = stationinfoEntity.getTaxpayerCode();
				
				camchangeEntity.setTaxpayerCode(taxpayerCode);
				
				
			}

		}

		return DataResult.success(iPage);
	}

	public String removeFirstAndLastChar(String s) {
		if (s.length() <= 2) {
			return ""; // 如果字符串长度小于等于2，则返回空字符串
		}
		String str = s.substring(1, s.length() - 1);
		String replaceAll = str.replaceAll("\\\\", "");
		return replaceAll;

	}

	private String sign(String url, Map<String, Object> parameter) throws UnsupportedEncodingException {
		if (!parameter.isEmpty()) {
			url = url + "?";
			for (String key : parameter.keySet()) {
				url = url + key + "=" + parameter.get(key) + "&";
			}
			url = url.substring(0, url.length() - 1);
		}

		String encrypt = MD5Utils.encrypt(pass);
		byte[] hmacSHA256 = HmacSha256Utils.hmacSHA256(url, encrypt);
		byte[] encodedBytes = Base64.getEncoder().encode(hmacSHA256);
		String encodedString = URLEncoder.encode(new String(encodedBytes), "UTF-8");

		return encodedString;
	}

}
